<template>
  <!-- 站点集合 赛事 打卡点集合 -->
  <div class="pageWrap">
    <div class="head">赛事站点集合</div>
    <p class="latlngtips">注* ：纬度范围为：3-54度，经度范围为：73-136</p>
    <el-table id="tab" :data="cpInfos" row-key="ind" style="width: 100%">
      <el-table-column label="站点" width="150">
        <template slot-scope="{row}">
          <el-input clearable v-model="row.name" placeholder="请输入站点" @input="$forceUpdate()"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="站点类型" width="150">
        <template slot-scope="{row}">
          <el-select v-model="row.type" placeholder="站点类型" @change="$forceUpdate()">
            <el-option v-for="item in pointType" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="名称" width="180">
        <template slot-scope="{row}">
          <el-input clearable v-model="row.cpName" placeholder="请输入站点名称" @input="$forceUpdate()"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="纬度">
        <template slot-scope="{row}">
          <el-input clearable style="margin-bottom:8px;" v-model="row.latA" placeholder="请输入度" @input="$forceUpdate()">
          </el-input>
          <el-input clearable v-model="row.latB" placeholder="请输入分" @input="$forceUpdate()"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="经度">
        <template slot-scope="{row}">
          <el-input clearable style="margin-bottom:8px;" v-model="row.lngA" placeholder="请输入度" @input="$forceUpdate()">
          </el-input>
          <el-input clearable v-model="row.lngB" placeholder="请输入分" @input="$forceUpdate()"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="海拔" width="150">
        <template slot-scope="{row}">
          <el-input clearable v-model="row.altitude" placeholder="请输入海拔"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="{row,$index}">
          <el-button type="text" v-if="bigType!='S'" @click="addDesc(row,$index)">添加描述</el-button>
          <el-button type="text" v-if="row.id&&ifScancard==1" @click="subjectModel(row.id)">问题设置</el-button>
          <el-button type="danger" icon="el-icon-delete" circle v-if="$index!=0" @click="delcp(row.id,$index)">
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top:15px;">
      <el-button @click="addPoint()">添加站点</el-button>
      <el-button type="primary" @click="savePoints()">保存</el-button>
      <el-button type="primary" @click="DownloadCode">
        <el-tooltip class="item" effect="dark" placement="bottom">
          <div slot="content">
            用于选手自己扫码打卡，无工作人员，需在赛事发布开启选手打卡
          </div>
          <span>
            导出站点二维码
            <i class="el-icon-question"></i>
          </span>
        </el-tooltip>
      </el-button>
    </div>
    <el-dialog title="问题设置" :visible.sync="problemVisible" width="80%" :close-on-click-modal="false">
      <p style="margin-bottom:10px;">选手扫码打卡将随机抽取以下一道题目进行答题，答对则打卡成功，错误则重新扫码答题</p>
      <el-button @click="addSubject()" size="small">添加题目</el-button>
      <p style="margin: 8px 0;"></p>
      <el-tabs v-model="questionInd" type="card" closable @tab-remove="removeTab">
        <el-tab-pane :label="'题目'+(i+1)" :name="v.name" v-for="v,i in subjectArr" :key="v.name">
          <el-form label-width="100px">
            <el-form-item label="类型">
              <el-radio-group v-model="v.type">
                <el-radio :label="1">选择题</el-radio>
                <!-- <el-radio :label="2">多选</el-radio> -->
                <el-radio :label="3">填空题</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item :label="'题目'+(i+1)+'：'">
              <el-input clearable v-model="v.questionContent" placeholder="请输入题目"></el-input>
              <!-- <RichTxt :ref="'questionEditor'+i"></RichTxt> -->
            </el-form-item>
            <template v-if="v.type!=3">
              <el-form-item label="选项A：">
                <el-input clearable v-model="v.resultA" placeholder="请输入选项A内容"></el-input>
              </el-form-item>
              <el-form-item label="选项B：">
                <el-input clearable v-model="v.resultB" placeholder="请输入选项B内容"></el-input>
              </el-form-item>
              <el-form-item label="选项C：">
                <el-input clearable v-model="v.resultC" placeholder="请输入选项C内容"></el-input>
              </el-form-item>
              <el-form-item label="选项D：">
                <el-input clearable v-model="v.resultD" placeholder="请输入选项D内容"></el-input>
              </el-form-item>
            </template>
            <el-form-item :label="'题目'+(i+1)+'答案：'">
              <el-input clearable v-model="v.result" :placeholder="'请输入题目'+(i+1)+'答案'"></el-input>
            </el-form-item>
            <el-form-item label="答案解析：">
              <el-input clearable v-model="v.analysis" :placeholder="'请输入题目'+(i+1)+'答案解析'"></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button @click="problemVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureSubject">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="站点描述" :visible.sync="dialogVisible" v-loading="descLoad" width="80%">
      <el-form label-width="100px">
        <el-form-item label="站点图片：">
          <el-upload ref="upbanner" class="cardUpImg" :action="upLoadUrl" :show-file-list="false"
            :on-success="picSuccess" :before-upload="beforeUpload" name="img">
            <img v-if="cpImg" :src="cpImg" class="cardImg" />
            <i v-else class="el-icon-plus card-icon"></i>
          </el-upload>
          <span class="tips">注：请上传jpg格式</span>

          <span class="tips del" v-if="cpImg" @click="delCpImg">删除图片</span>
          <!-- <el-button type="text" style="float:left;" v-if="cpImg" @click="delCpImg">删除图片</el-button> -->
        </el-form-item>
        <el-form-item label="站点简介：">
          <!-- <el-input
            type="textarea"
            placeholder="请输入内容"
            v-model="cpInfo"
            maxlength="200"
            show-word-limit
          ></el-input>-->
          <RichTxt ref="editor"></RichTxt>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureDesc">确 定</el-button>
      </div>
    </el-dialog>
    <div id="erCode"></div>
  </div>
</template>

<script>
  import QRCode from "qrcodejs2";
  import JSZip from "jszip";
  import FileSaver from "file-saver";
  var cpInit = {
    id: 0,
    ind: 1,
    name: "", // 站点
    type: "D", // 站点类型
    cpName: "", // 名称
    lng: "", // 经度
    lat: "", //纬度
    latA: "", // 纬度 度
    latB: "", // 纬度 分
    lngA: "", // 经度 度
    lngB: "", //经度 分
    altitude: "", // 海拔
    uid: 1, // row-key 唯一标识 下标加1 排序
    cpImg: "",
    cpInfo: "",
  };
  // import Sortable from "sortablejs";

  //富文本
  import RichTxt from "../../../../components/editor/editor";
  export default {
    components: {
      RichTxt
    },
    data() {
      return {
        isDown: false,
        qrcodeArr: [],
        cpInfos: [],
        pointType: [{
            value: "D",
            label: "打卡点",
          },
          {
            value: "F",
            label: "服务点",
          },
          {
            value: "Q",
            label: "其他",
          },
        ],
        bigType: "S",
        dialogVisible: false,
        descInd: 0,
        upLoadUrl: this.$url + "/sbr/match/uploadImg",
        cpImg: "",
        // cpInfo: "",
        descLoad: false,
        problemVisible: false,
        ifScancard: 0,
        subjectArr: [],
        questionInd: '', //当前选中的题目
        subjectcpId: ''
      };
    },
    methods: {
      // 添加站点
      addPoint() {
        cpInit.ind = this.cpInfos.length + 1;
        cpInit.uid = this.cpInfos.length + 1;
        this.cpInfos.push(JSON.parse(JSON.stringify(cpInit)));
      },
      // 删除站点
      delcp(id, index) {
        if (id == 0) {
          this.cpInfos.splice(index, 1);
        } else {
          this.$axios.get("/sbr/match/delMatchCp?id=" + id).then((res) => {
            this.cpInfos.splice(index, 1);
          });
        }
      },
      // 保存
      savePoints() {
        let emptyIt = this.cpInfos.findIndex((v) => {
          return v.name == "" && v.cpName == "";
        });
        if (emptyIt >= 0) {
          this.$message.error("站点及站点名称不可为空");
          return false;
        }
        this.cpInfos.forEach((v) => {
          if (!v.latA) {
            v.latA = 0;
          }
          if (!v.latB) {
            v.latB = 0;
          }
          if (!v.lngA) {
            v.lngA = 0;
          }
          if (!v.lngB) {
            v.lngB = 0;
          }
          v.lat = (Number(v.latA) + Number(v.latB) / 60).toFixed(6);
          v.lng = (Number(v.lngA) + Number(v.lngB) / 60).toFixed(6);
          v.lat = Number(v.lat);
          v.lng = Number(v.lng);
          v.altitude = Number(v.altitude);
        });
        // 纬度范围为：3-54度，经度范围为：73-136
        let warn_lat_lng = this.cpInfos.find((v) => {
          if (
            v.lng != 0 &&
            v.lat != 0 &&
            (v.lng < 73 || v.lng > 136 || v.lat < 3 || v.lat > 54)
          )
            return v;
        });
        if (warn_lat_lng) {
          this.$alert("经纬度范围有误，请核验后提交", "提示", {
            confirmButtonText: "确定",
          });
        } else {
          let putObj = {
            id: Number(
              Number(this.$Base64.decode(sessionStorage.getItem("MandA")))
            ),
            matchCpInfos: this.cpInfos,
          };
          this.$axios.post("/sbr/match/setMatchCpInfo", putObj).then((res) => {
            this.$message.success("保存成功");
            this.getcpInfos();
          });
        }
      },
      getcpInfos() {
        this.$axios
          .get("/sbr/match/getMatchCpList/" + sessionStorage.getItem("MandA"))
          .then((res) => {
            let rr = res.data.data;
            rr.forEach((v, i) => {
              v.latA = v.lat ? v.lat : "";
              v.lngA = v.lng ? v.lng : "";
              v.altitude = v.altitude ? v.altitude : "";
              v.ind = i + 1;
            });
            this.cpInfos = rr;
            if (rr.length == 0)
              this.cpInfos = [JSON.parse(JSON.stringify(cpInit))];
          });
      },
      addDesc(row, ind) {
        this.dialogVisible = true;
        this.descLoad = true;
        setTimeout(() => {
          this.descInd = ind;
          this.cpImg = row.cpImg;
          // this.cpInfo = row.cpInfo;
          this.$refs.editor.content = row.cpInfo;
          this.descLoad = false;
        }, 500);
        // console.log(this.cpImg);
        this.$forceUpdate();
      },

      picSuccess(v) {
        this.cpImg = v.data.filePath;
      },
      beforeUpload(file) {
        const isJPG = file.type === "image/jpeg";
        const isLt1M = file.size / 1024 / 1024 < 1;

        if (!isJPG) {
          this.$message.error("上传图片只能是 JPG 格式!");
        }
        if (!isLt1M) {
          this.$message.error("上传图片大小不能超过 1MB!");
        }
        return isJPG && isLt1M;
      },
      delCpImg() {
        let pp = this.cpImg.split("/");
        pp = this.$Base64.encode(pp[pp.length - 1]);
        this.$axios.get("/sbr/match/delImg?fileName=" + pp).then((res) => {
          this.cpImg = "";
        });
      },
      sureDesc() {
        this.cpInfos[this.descInd].cpImg = this.cpImg;
        this.cpInfos[this.descInd].cpInfo = this.$refs.editor.content;
        this.dialogVisible = false;
      },

      // 生成二维码
      qrcode(el, data) {
        let qrcode = new QRCode(el, {
          width: 200,
          height: 200, // 高度
          text: data
        })
      },
      // 下载二维码
      DownloadCode() {
        if (this.isDown) return
        this.isDown = true
        let erCode = document.getElementById('erCode')
        this.cpInfos.forEach((v, i) => {
          let el = document.createElement('div')
          el.id = 'qrcode' + i
          el.style.display = 'none'
          erCode.appendChild(el)
          let obj = {
            id: v.id,
            matchId: v.matchId,
            name: v.name,
            cpName: v.cpName,
            lng: v.lng,
            lat: v.lat
          }
          this.qrcode(el.id, JSON.stringify(obj));
          let myCanvas = el.getElementsByTagName('canvas');
          this.qrcodeArr.push({
            name: v.name + '_' + v.cpName,
            url: myCanvas[0].toDataURL('image/jpg')
          })
        })
        // console.log(this.qrcodeArr)
        this.packageImages()
      },
      // 多个二维码图片生成压缩包并下载下来
      packageImages() {
        let that = this;
        const zip = new JSZip();
        const cache = {};
        setTimeout(() => {
          let arr = that.qrcodeArr;
          arr.forEach((item, index) => {
            let fileName = item.name;
            zip.file(fileName + ".png", item.url.substring(22), {
              base64: true
            });
            cache[fileName] = item.url;
          });
          // 下载压缩包
          zip.generateAsync({
            type: "blob"
          }).then(content => {
            FileSaver.saveAs(content, "二维码.zip");
            document.getElementById('erCode').innerHTML = ''
            this.isDown = false
          });
        }, 0);
      },

      getGroupArr() {
        this.$axios
          .get("/sbr/match/getMatchInfos/" + sessionStorage.getItem("MandA"))
          .then((res) => {
            let rr = res.data.data;
            this.ifScancard = rr.ifScancard
          });
      },
      // 问题设置 打开弹框
      subjectModel(cpid) {
        this.subjectcpId = cpid
        this.$axios.get('/sbr/match/selectCpQuestions?cpId='+cpid).then(res=>{
          let rr=res.data.data
          console.log(rr);

          this.subjectArr=rr
        // 查询该点下的问题 如果是空先调添加
        if (this.subjectArr.length == 0) this.addSubject()
        this.subjectArr.forEach((v,i)=>{
          if(!v.name)v.name='tab'+(new Date().getTime()-(i+1)*10)
        })
        this.questionInd=this.subjectArr[0].name
        this.problemVisible = true
        })
      },
      removeTab(targetName) {
        console.log(targetName)
        let i=this.subjectArr.findIndex(s=>{return s.name==targetName})
        let id=this.subjectArr[i].id
        if(id!=0){
        this.$axios.get('/sbr/match/deleteCpQuestions?cpIds='+id).then(res=>{
          let rr=res.data
          if(rr.code!=200){
            this.$message.error(rr.msg)
            return
          }
          this.subjectArr.splice(i,1)
        })
        }else this.subjectArr.splice(i,1)
        
      },
      addSubject() {
        if (this.subjectArr.length >= 8) {
          this.$message.error('最多添加八道问题')
          return
        }
        this.subjectArr.push({
          id: 0,
          cpId: this.subjectcpId,
          questionContent: '',
          resultA: '',
          resultB: '',
          resultC: '',
          resultD: '',
          result: '',
          type: 1,
          analysis: '', //答案解析
          name:'tab'+new Date().getTime()
        })
        console.log(this.subjectArr)
      },
      sureSubject(){
        this.subjectArr.forEach((v,i)=>{
          // console.log(this.$refs[`questionEditor${v.name}`][i].content,`questionEditor${v.name}`,this.$refs);
          // v.questionContent=this.$refs[`questionEditor${i}`].content;
          if(v.type==3){
            v.resultA=''
          v.resultB=''
          v.resultC=''
          v.resultD=''
          }
        })
        // console.log(this.subjectArr)
        this.$axios.post('/sbr/match/putCpQuestion',this.subjectArr).then(res=>{
          this.problemVisible=false
        })
      }
    },
    mounted() {
      // let that = this;
      // setTimeout(() => {
      //   that.rowDrop();
      // }, 100);
      this.bigType = this.$Base64.decode(sessionStorage.getItem("mold"));
      this.getGroupArr()
      this.getcpInfos();
    },
  };
</script>
<style scoped>
  .head {
    font-size: 18px;
    color: #303133;
  }

  .latlngtips {
    line-height: 30px;
    color: red;
  }

  .tab {
    width: 100%;
    line-height: 40px;
  }

  .cardUpImg {
    width: 200px;
    height: 123px;
    float: left;
  }

  .cardUpImg>>>.el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .cardUpImg>>>.el-upload:hover {
    border-color: #409eff;
  }

  .card-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 123px;
    line-height: 123px;
    text-align: center;
  }

  .cardImg {
    width: 200px;
    height: 123px;
    display: block;
  }

  .tips {
    font-size: 12px;
    float: left;
    line-height: 1.2;
    margin-left: 10px;
    cursor: pointer;
  }

  .tips.del:hover {
    color: #409eff;
  }
</style>